package cn.tedu.oa.common.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.tedu.oa.common.annotation.LogAnnotation;
import cn.tedu.oa.sys.dao.LogDao;

public class SysLogInterceptor implements HandlerInterceptor{
	
	@Autowired
	private LogDao logDao;

	public SysLogInterceptor() {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod hMethod=(HandlerMethod) handler;
		LogAnnotation annotation = hMethod.getMethodAnnotation(LogAnnotation.class);
		if (annotation!=null) {
			long startTime = System.nanoTime();
			request.setAttribute("startTime", startTime);
		}
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//		System.out.println(handler.getClass().getName());
		HandlerMethod hMethod=(HandlerMethod) handler;
		LogAnnotation annotation = hMethod.getMethodAnnotation(LogAnnotation.class);
		long endTime = 0,startTime = 0;
		if(annotation!=null){
			Method method = hMethod.getMethod();
			//用户名
			String username="sunbiao";
			//方法描述
			String value=annotation.value();
			endTime= System.nanoTime();
			startTime=(Long)request.getAttribute("startTime");
		    String className=hMethod.getBeanType().getSimpleName();
			System.out.println(method.getDeclaringClass().getSimpleName());
			System.out.println(method.getClass().getSimpleName());
			System.out.println(hMethod.getBeanType().getSimpleName());
			System.out.println(method.getName()+"执行总时长："+(endTime-startTime));
		}
			
	}
}
